package  com.fbi;

import com.microstrategy.web.app.AbstractExternalSecurity;
import com.microstrategy.web.app.ExternalSecurity;
import com.microstrategy.web.app.beans.EnumServletEvents;
import com.microstrategy.web.beans.GenericWebEvent;
import com.microstrategy.web.beans.RequestKeys;
import com.microstrategy.web.objects.WebIServerSession;
import com.microstrategy.web.objects.WebObjectsFactory;
import com.microstrategy.web.platform.ContainerServices;


public class MultipleProject extends AbstractExternalSecurity {
	
	
	
	public MultipleProject() {
		super();
	}

	public String getFailureURL(int reqType, ContainerServices cntrSvcs)
	{
		switch( reqType)
		{
			case ExternalSecurity.AUTHENTICATION_REQUEST:
				System.out.println("ExternalSecurity.AUTHENTICATION_REQUEST");
				break;
			case ExternalSecurity.AUTHORIZATION_REQUEST :
				System.out.println("ExternalSecurity.AUTHORIZIATION_REQUEST");
				break;
		}
		return cntrSvcs.getApplicationPath()+"/mstrWeb?evt=3008&src=mstrWeb.3008";
	}

	public String getCustomLoginURL(String originalURL,String desiredServer, int desiredPort, String desiredProject)
	{
		try{
		System.out.println("originalURL" + originalURL);
		System.out.println("desiredServer" + desiredServer);
		System.out.println("desiredPort" + desiredPort);
		System.out.println("desiredProject" +desiredProject);
		}catch(Exception e)
		{}
		return  "/servlet/mstrWeb?evt=3008&src=mstrWeb.3008";
		
	}
	
	public int handlesAuthenticationRequest(RequestKeys reqKeys, ContainerServices cntSvcs, int reason) 
	{
   		int ret=ExternalSecurity.USE_CUSTOM_LOGIN_PAGE ;
   		switch(reason)
   		{
  			
   				
   			case ExternalSecurity.INVALID_CREDENTIALS :
   				System.out.println("ExternalSecurity.INVALID_CREDENTIALS");
   				break;
   			case ExternalSecurity.SESSION_CLOSED :
  				System.out.println("ExternalSecurity.SESSION_CLOSED");
   				ret = ExternalSecurity.COLLECT_SESSION_NOW;
  				break;
   			case ExternalSecurity.NO_SESSION_FOUND :
   				System.out.println("ExternalSecurtity.NO_SESSION_FOUND");
  				ret = ExternalSecurity.COLLECT_SESSION_NOW;
  				break;
  		}
      	
   		return ret;
	}
	

	public WebIServerSession getWebIServerSession(RequestKeys reqKeys,  ContainerServices cntSvcs) 
	{
		System.out.println("\n\n*****************GetWebIServerSession***********************\n");
		 /* if(!reqKeys.isEmpty())
		  {
		  
		  	for( int i=0; i< reqKeys.getNameCount();i++)
		  	{
		  	 try {
		  		System.out.println("the request "+ reqKeys.getName(i)+"==" + reqKeys.getValue(reqKeys.getName(i)));
		  	}catch(Exception e )
		  	{}	
		        }
		  } */
		WebIServerSession isess = null;
		
		for(int i=0;i<reqKeys.getValueCount("Project");i++)
		{
			System.out.println("project["+i+"] ---"+reqKeys.getValue("Project",i));
		}
		
		String prjName =  reqKeys.getValue("Project",0);	
		if( cntSvcs.getSessionAttribute(prjName+"_111")!=null)
		{
			System.out.println("get the exist one ");
			isess = (WebIServerSession)cntSvcs.getSessionAttribute(prjName+"_111");
			System.out.println("Session ProjectName is --" +isess.getProjectName());
		}

		if( isess == null )
	  	{
	      	  	System.out.println("\n *************** \n  to get new one");
	      	  	isess = WebObjectsFactory.getInstance().getIServerSession();
	        	
	        	try {
		          	String uid = reqKeys.getValue("uid",0);
			        String LDAP_prj = reqKeys.getValue("Prj",0);
			        cntSvcs.setSessionAttribute("FolderID",LDAP_prj );
			        	
			        // 需要在这里进行用户的Mapping 同时为了后续的权限处理，需要将这些信息设在Session中。
			        // 用户的Mapping处理可能需要访问数据库表，注意这里为demo的需要仅仅用常量。
		        	isess.setLogin("administrator");
				isess.setPassword("");
				 
				System.out.println("=="+reqKeys.getValue("Project")+"--"+reqKeys.getValue("Server")+"--"+LDAP_prj);
					
				isess.setProjectName(reqKeys.getValue("Project",0));
				isess.setServerName(reqKeys.getValue("Server",0));
				     
				if( reqKeys.getValue("Port",0) == null )
				        isess.setServerPort(0);
				else
				        isess.setServerPort(Integer.parseInt(reqKeys.getValue("Port",0)));
				System.out.println("To get session...");
		    	}catch(Exception e)
		    	{
			   isess =  null;
			   System.out.println("error occur! ");
			   e.printStackTrace();
		   	 }
		}
		
		cntSvcs.setSessionAttribute(prjName+"_111",isess);
		return isess;
	
    } 
   
   
	public boolean isRequestAuthorized(RequestKeys reqKeys, ContainerServices cntSvcs, WebIServerSession sess)
	{
		
		System.out.println("************** Call isRequestAuthorized *************************");
		
		/*  if(!reqKeys.isEmpty())
		  {
		  
		  	for( int i=0; i< reqKeys.getNameCount();i++)
		  	{
		  	 try {
		  		System.out.println("the request "+ reqKeys.getName(i)+"==" + reqKeys.getValue(reqKeys.getName(i)));
		  	}catch(Exception e )
		  	{}	
		        }
		  } */
		System.out.println("Call isRequestAuthorized!");
		System.out.println("Session ProjectName is --" +sess.getProjectName());
		return true;
/*		if (isLogoutRequest(reqKeys))  
		{
	    	 try {
			    	if(sess != null ) sess.closeSession(); 	 
			 } catch (WebObjectsException woe) {
	               System.err.println(woe.getMessage());
	         }  	
	    	}
	    	System.out.println("Session ProjectName is --" +sess.getProjectName());
	    	if("MicroStrategy Tutorial".equals(sess.getProjectName()))
			return true;
		else
			sess= (WebIServerSession)cntSvcs.getSessionAttribute("Customer Analysis Module_111");
		return sess != null ;
*/	}



	private boolean isLogoutRequest(RequestKeys reqKeys) {
		String strValue = reqKeys.getValue(GenericWebEvent.URL_EVENT_NAME);

		if ((strValue == null) || strValue.equals("")) {
			return false;
		}

		int intValue = -1;

		try {
			intValue = Integer.parseInt(strValue);
		} catch (NumberFormatException nfe) {
			return false;
		}

		if (intValue == EnumServletEvents.WebEventLogout) {
			return true;
		}

		return false;
	}
	
}
